import socket


class UdpManager:
    def __init__(self, target_ip: str, target_port: int):
        try:
            self.__target_ip = target_ip
            self.__target_port = target_port
            self.__socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            bind_addr = ("0.0.0.0", self.__target_port)
            self.__socket.bind(bind_addr)
            self.__socket.settimeout(10)
        except Exception as e:
            print(e)
            self.__socket = None
            pass

    def udp_close(self):
        self.__socket.close()

    def get_socket(self):
        return self.__socket

    def recv_udp_data(self):
        try:
            # 接收服务器的响应
            data, addr = self.__socket.recvfrom(65536)
            print(f"收到来自 {addr} 的响应: {data.decode()}")
            return data
        except socket.timeout:
            print("接收等待响应超时！")

    def send_udp_data(self, message: str):
        try:
            # 发送数据到目标地址
            self.__socket.sendto(message.encode(), (self.__target_ip, self.__target_port))
            print(f"已发送消息到 {self.__target_ip}:{self.__target_port}: {message}")
            # 设置超时（可选，避免无限等待）
            #self.__socket.settimeout(2)  # 2 秒超时
        except socket.timeout:
            print("等待响应超时！")
        # finally:
        #     self.__socket.close()
